package com.siashan.toolkit.sms.qiniu;

import com.siashan.toolkit.sms.cache.SmsCacheAutoConfiguration;
import com.siashan.toolkit.sms.cache.SmsCacheTemplate;
import com.siashan.toolkit.sms.core.entity.SmsFrequencyLimitConfig;
import com.siashan.toolkit.sms.core.entity.SmsTemplate;
import com.siashan.toolkit.sms.core.entity.SmsWhiteList;
import com.siashan.toolkit.sms.core.utils.SmsTemplateUtils;
import com.siashan.toolkit.sms.qiniu.core.QiniuSmsConfig;
import com.siashan.toolkit.sms.qiniu.core.QiniuSmsSendExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.List;
import java.util.Map;

/**
 * 七牛云发送端点自动配置
 *
 * @author siashan
 * @since v1.0.1
 */
@Configuration
@EnableConfigurationProperties(QiniuSmsProperties.class)
@Import(SmsCacheAutoConfiguration.class)
public class QiniuSmsAutoConfiguration {


    @Autowired
    private QiniuSmsProperties qiniuSmsProperties;

    @Autowired
    private SmsCacheTemplate smsCacheTemplate;

    /**
     * 构造七牛云发送处理
     *
     * @return 七牛云发送处理
     */
    @Bean
    @ConditionalOnMissingBean
    public QiniuSmsSendExecutor qiniuSmsSendExecutor() {
        List<SmsTemplate> templateList = qiniuSmsProperties.getTmpls();
        Map<String, SmsTemplate> templateMap = SmsTemplateUtils.transMap(templateList);
        QiniuSmsConfig config = qiniuSmsProperties.getConfig();
        SmsWhiteList whiteList = qiniuSmsProperties.getWhiteList();
        SmsFrequencyLimitConfig frequencyLimit = qiniuSmsProperties.getFrequencyLimit();
        QiniuSmsSendExecutor executor = new QiniuSmsSendExecutor(config,templateMap, whiteList,frequencyLimit);
        return executor;
    }

    /**
     * 构造七牛云发送模板类
     *
     * @return 七牛云发送模板类
     */
    @Bean
    @ConditionalOnMissingBean
    public QiniuSmsTemplate qiniuSmsTemplate() {
        QiniuSmsTemplate qiniuSmsTemplate = new QiniuSmsTemplate(smsCacheTemplate,qiniuSmsSendExecutor());
        return qiniuSmsTemplate;
    }

}
